package com.ly.algorithm.DataStructures.linkedlist;

/**
 * @Classname Josepfu
 * @Description TODO
 * @Date 2020/4/22 10:34
 * @Author 冷心影翼
 */
public class Josepfu {

    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoyByNum(1000000);
        circleSingleLinkedList.list();
        circleSingleLinkedList.countBoy(1,2,1000000);

    }


}


class CircleSingleLinkedList {
    private Boy first = null;


    public void addBoyByNum(int num) {
        if(num<1) {
            System.out.println("num错误");
            return;
        }
        Boy cur = null;
        for(int i=1;i<=num;i++) {
            Boy boy = new Boy(i);
            if (i==1) {
                first = boy;
                first.next = first;
                cur = first;
            } else {
                boy.next = first;
                cur.next = boy;
                cur = cur.next;
            }
        }

    }


    public void list() {
        if(first == null) {
            System.out.println("链表为空");
            return;
        }
        Boy cur = first;
        while (true) {
            System.out.println(cur);
            if(cur.next == first) {
                break;
            }

            cur = cur.next;
        }
    }

    public void countBoy(int startNo,int countNum,int nums) {
        if(first == null || startNo<1 || startNo>nums) {
            System.out.println("参数出错");
            return;
        }
        Boy helper = first;
        //将 helper 位移 到 first 的后方
        while (true) {
            if( helper.next == first) {
                break;
            }
            helper = helper.next;
        }
        //改变初始位置
        for(int i=1;i<startNo;i++) {
            helper = helper.next;
            first = first.next;
        }

        while (true) {
            //只有一个节点
            if(helper == first) {
                System.out.println("最后一个小孩"+first);
                break;
            }
            for(int i=0;i<countNum-1;i++) {
                first = first.next;
                helper = helper.next;
            }
            System.out.println(first);
            //重新指向删除节点的下一个节点
            first = first.next;
            helper.next = first;
        }
    }
}

class Boy {
    public int no;

    public Boy next;

    public Boy(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "Boy " +
                "no=" + no+
               " next.no="+next.no;
    }
}